package com.laboratory.concurrent;

import com.laboratory.thread.TaskEngine;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class CountDownLatchTest {

    public static void main(String[] args) {


        for (int i = 0; i < 5; i++) {

            System.out.println("----begin---" +i);


            CountDownLatch latch = new CountDownLatch(2);


            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {

                        System.out.println("子线程" + Thread.currentThread().getName() + "正在执行");
                        Thread.sleep(1000);
                        System.out.println("子线程" + Thread.currentThread().getName() + "执行完毕");
                        latch.countDown();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            t1.setName("t1-" +i);
            t1.start();

            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {

                        System.out.println("子线程" + Thread.currentThread().getName() + "正在执行");
                        Thread.sleep(2000);
                        System.out.println("子线程" + Thread.currentThread().getName() + "执行完毕");
                        latch.countDown();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            t2.setName("t2-"+i);
            t2.start();

            try {
                System.out.println("等待t1和t2子线程执行完毕...");
                boolean await = latch.await(2, TimeUnit.SECONDS);
                System.out.println("t1和t2子线程已经执行完毕" +await);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }


}
